package kubernetes

import (
	"context"
	"errors"
	"fmt"
	"k8s-admin/global"
	"k8s-admin/utils"
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type NodesResp struct {
	Items []corev1.Node `json:"items"`
	Total int           `json:"total"`
}

func (n *k8sCluster) GetK8sClusterNodeList(cid, name string, page, limit int) (nodeResp []map[string]interface{}, err error) {
	clientset, err := utils.GetCache(cid)
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return nil, err
	}

	var (
		ctx    context.Context
		cancel context.CancelFunc
	)
	ctx, cancel = context.WithTimeout(context.TODO(), time.Second*5)
	defer cancel()
	list, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
	if err != nil {
		global.TPLogger.Error(err)
		return nil, err
	}
	for _, item := range list.Items {
		nodeMemory := item.Status.Capacity.Memory().Value()/1024/1024/1024 + 1
		resource := fmt.Sprintf("%sCore %dGB", item.Status.Capacity.Cpu().String(), nodeMemory)
		// item.Status.
		nodeResp = append(nodeResp, map[string]interface{}{
			"name":       item.Name,
			"labels":     item.Labels,
			"status":     item.Status.Conditions[len(item.Status.Conditions)-1].Type,
			"ip":         item.Status.Addresses[0].Address,
			"createTime": item.CreationTimestamp.Time.Format(time.DateTime),
			"version":    item.Status.NodeInfo.KubeletVersion,
			"resource":   resource,
		})
	}

	return nodeResp, nil
}

func (n k8sCluster) GetK8sClusterNodeDetail(cid string, name string) (node *corev1.Node, err error) {
	clientset, err := utils.GetCache(cid)
	if err != nil {
		global.TPLogger.Error("Node管理模块获取节点:", errors.New("当前集群不存在"))
		return nil, err
	}

	var (
		ctx    context.Context
		cancel context.CancelFunc
	)
	ctx, cancel = context.WithTimeout(context.TODO(), time.Second*5)
	defer cancel()
	get, err := clientset.CoreV1().Nodes().Get(ctx, name, metav1.GetOptions{})
	if err != nil {
		return nil, err
	} else {
		return get, nil
	}
}
